package com.matt.service.courseV2.impl;

import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.domain.courseV2.*;
import com.matt.domain.courseV2.po.*;
import com.matt.foundation.constant.FeedsConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.CopyUtils;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.repository.courseV2.*;
import com.matt.service.FeedsService;
import com.matt.service.courseV2.DevelopReviewService;
import com.tuo51.foudation.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DevelopReviewServiceImpl implements DevelopReviewService {


    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    private DevelopReviewRepository developReviewRepository;

    @Autowired
    private DevelopUserRepository developUserRepository;

    @Autowired
    private DevelopUserRecordRepository developUserRecordRepository;

    @Autowired
    private DevelopReviewItemRepository developReviewItemRepository;

    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Autowired
    private FeedsService feedsService;

    @Override
    public List<DevelopReview> monthList(Integer type) {
        if (Objects.nonNull(type)){
            return developReviewRepository.findByTypeOrderByOrderNumAsc(type);
        }
        return developReviewRepository.findByOrderByOrderNumAsc();
    }

    @Override
    public List<DevelopReviewItem> monthItemList(String developId) {
        return developReviewItemRepository.findByDevelopIdOrderByOrderNumAsc(developId);
    }

    @Override
    @Transactional
    public void addUserMonth(StaffDTO staff,String childrenIds, String classIds, String developId, String name, String remarks, List<DevelopUserRecordPO> list) {
        String[] ids =  childrenIds.split(",");
        List<Children> childrenList = childrenRepository.findByIdIn(ids);

        String[] ids1 =  classIds.split(",");
        List<Classes> classList = classesRepository.findByIdIn(ids1);
        if (Objects.isNull(childrenList)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "学生不存在");
        }
        if (Objects.isNull(classList)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "班级不存在");
        }
        DevelopReview developReview = developReviewRepository.getOne(developId);
        if (Objects.isNull(developReview)){
            throw new BusinessException(ErrorCode.IS_TARGET, "核检对象不存在！");
        }

        for (int i = 0; i < childrenList.size(); i++) {
            DevelopUser developUser  = developUserRepository.findAllByChildrenIdAndDevelopId(childrenList.get(i).getId(),developId);
            if (Objects.isNull(developUser)){
                developUser   = new DevelopUser();
                //先添加获取ID
                developUser = developUserRepository.save(developUser);
            }
            List<DevelopUserRecord> list1 = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                DevelopUserRecord developUserRecord = new DevelopUserRecord();
                if (Objects.nonNull(list.get(j).getId())){
                    developUserRecord =  developUserRecordRepository.getOne(list.get(j).getId());
                }
                CopyUtils.copyProperties(list.get(j),developUserRecord);
                developUserRecord.setDevelopId(developId);
                developUserRecord.setChildrenId(childrenList.get(i).getId());
                developUserRecord.setDevelopUserId(developUser.getId());
                list1.add(developUserRecord);
            }
            developUserRecordRepository.saveAll(list1);

            String sql = String.format("SELECT count(id) FROM `tc_develop_review_item` where developId=  '%s' ",developId);
            List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
            int developCount = Integer.parseInt(String.valueOf(objects1.get(0)));

            String sql2 = String.format("SELECT count(id) FROM `tc_develop_user_record` where developId=  '%s' ",developId);
            sql2 += String.format("and  childrenId=  '%s' ",childrenList.get(i).getId());
            List<Object[]> objects2 = baseNativeSqlRepository.sqlArrayList(sql2);
            int developNumber = Integer.parseInt(String.valueOf(objects2.get(0)));


            developUser.setChildrenId(childrenList.get(i).getId());
            developUser.setDevelopId(developId);
            developUser.setDevelopCount(developCount);
            developUser.setDevelopNumber(developNumber);
            developUser.setRemarks(remarks);
            developUser.setClassId(ids1[i]);
            developUser.setCreatedBy(name);
            developUserRepository.save(developUser);
            Children children  = childrenRepository.getOne(childrenList.get(i).getId());
            feedsService.save(staff.getId(), childrenList.get(i).getId(), staff.getAreaId(), "", FeedsConstant.DEVELOP_REVIEW, children.getName()+"的"+developReview.getName(), "","", "", developUser.getId());
        }

    }



    @Override
    public Page<DevelopCountPO> count(String areaId, String classId, String name, PagerQuery pagerQuery) {

        String sql = "SELECT c.id,c.`name`,cs.id as classId,cs.`name` as className,IFNULL(COUNT(du.id),0) as count,c.aid FROM  children c  " +
                "LEFT JOIN  rel_classes_children rcc on c.id = rcc.childrenId   " +
                "LEFT JOIN classes cs  on cs.id  = rcc.classesId   LEFT JOIN  tc_develop_user du on c.id = du.childrenId    where cs.areaId= '" +areaId+
                "' and c.id is not null ";
        if (Objects.nonNull(name)) {
            sql += String.format(" and c.name like concat('%s', '%s', '%s') ", "%", name, "%");
        }

        if (Objects.nonNull(classId)){
            sql += String.format("  and cs.id = '%s' ", classId);
        }

        sql += "   GROUP BY c.id    ORDER BY du.created DESC ";

        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
        sql += String.format("  limit %s, %s ", pagerQuery.getPageNum() * pagerQuery.getPageSize() ,  pagerQuery.getPageSize());

        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<DevelopCountPO> list = new ArrayList<>();
        for (int i = 0; i <objects.size() ; i++) {
            DevelopCountPO countPO = new DevelopCountPO();
            countPO.setChildrenId(objects.get(i)[0].toString());
            countPO.setChildrenName(objects.get(i)[1].toString());
            countPO.setClassesId(objects.get(i)[2].toString());
            countPO.setClassName(objects.get(i)[3].toString());
            countPO.setCount(Integer.valueOf(objects.get(i)[4].toString()));
            list.add(countPO);
        }
        return new PageImpl<>(list, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), objects1.size());
    }

    @Override
    public Page<DevelopDetailsListPO> childrenDetailsList(String childrenId, PagerQuery pagerQuery) {

        Children children = childrenRepository.getOne(childrenId);
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "宝宝不存在");
        }

        String sql = "SELECT du.childrenId,du.developId,du.createdBy,IFNULL(dr.`month`,0) as month ,du.created,du.id as developUserId,dr.type  FROM `tc_develop_user` du LEFT JOIN tc_develop_review dr on du.developId = dr.id" +
                "  where du.childrenId= '" +childrenId+"' ORDER BY du.created DESC ";
        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
        sql += String.format("  limit %s, %s ", pagerQuery.getPageNum() * pagerQuery.getPageSize() ,  pagerQuery.getPageSize());

        List<DevelopDetailsListPO> list = baseNativeSqlRepository.sqlObjectList(sql,DevelopDetailsListPO.class);
        for (int i = 0; i < list.size(); i++) {
            double actualMonth = DateUtil.betweenMonthsV2(list.get(i).getCreated(),children.getBirthday() );
            list.get(i).setChildrenMonth((int)actualMonth);
        }
        return new PageImpl<>(list, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), objects1.size());

    }


    @Override
    public DevelopDetailsPO childrenDetails(String developUserId) {

        DevelopUser developUser = developUserRepository.getOne(developUserId);
        if (Objects.isNull(developUser)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "记录不存在");
        }
        Children children = childrenRepository.getOne(developUser.getChildrenId());
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "宝宝不存在");
        }
        DevelopReview developReview  = developReviewRepository.getOne(developUser.getDevelopId());
        if (Objects.isNull(developReview)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "检查项不存在");
        }
        DevelopDetailsPO developDetailsPO = new DevelopDetailsPO();

        developDetailsPO.setChildren(children);
        developDetailsPO.setChildrenId(children.getId());
        developDetailsPO.setMonth(developReview.getMonth());
        double actualMonth = DateUtil.betweenMonthsV2(developUser.getCreated(), children.getBirthday());
        developDetailsPO.setChildrenMonth((int)actualMonth);
        developDetailsPO.setHeadImg(children.getImgUrl());
        developDetailsPO.setChildrenName(children.getName());
        developDetailsPO.setRemarks(developUser.getRemarks());
        developDetailsPO.setCreatedBy(developUser.getCreatedBy());
        developDetailsPO.setType(developReview.getType());
        String sql = "SELECT dri.`name`,dri.monthAge,du.states,IFNULL(dri.target,''),IFNULL(dri.details,''),dri.id  FROM `tc_develop_user_record` du INNER JOIN  tc_develop_review_item dri on du.developItemId = dri.id" +
                "  where du.developUserId= '" +developUserId+"'  ORDER BY  dri.`name` ";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);

        List<DevelopItemDetailsPO> list = new ArrayList<>();
        for (int i = 0; i <objects.size() ; i++) {
            DevelopItemDetailsPO developItemDetails = new DevelopItemDetailsPO();
            developItemDetails.setName(objects.get(i)[0].toString());
            developItemDetails.setMonthAge(Integer.valueOf(objects.get(i)[1].toString()));
            developItemDetails.setStates(Integer.valueOf(objects.get(i)[2].toString()));
            developItemDetails.setTarget(objects.get(i)[3].toString());
            developItemDetails.setDetails(objects.get(i)[4].toString());
            developItemDetails.setItemId(objects.get(i)[5].toString());
            list.add(developItemDetails);
        }
        developDetailsPO.setList(list);
        return developDetailsPO;
    }

    @Override
    public void addUserMonth1(StaffDTO staff, String childrenIds, String classIds, String developId, String realName, String remarks, List<DevelopUserRecordPO> list, Integer developName) {
        String[] ids =  childrenIds.split(",");
        List<Children> childrenList = childrenRepository.findByIdIn(ids);

        String[] ids1 =  classIds.split(",");
        List<Classes> classList = classesRepository.findByIdIn(ids1);
        if (Objects.isNull(childrenList)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "学生不存在");
        }
        if (Objects.isNull(classList)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "班级不存在");
        }
        DevelopReview developReview = developReviewRepository.getOne(developId);
        if (Objects.isNull(developReview)){
            throw new BusinessException(ErrorCode.IS_TARGET, "核检对象不存在！");
        }
        developReview.setMonth(developName);
        developReviewRepository.save(developReview);

        for (int i = 0; i < childrenList.size(); i++) {
            DevelopUser developUser  = developUserRepository.findAllByChildrenIdAndDevelopId(childrenList.get(i).getId(),developId);
            if (Objects.isNull(developUser)){
                developUser   = new DevelopUser();
                //先添加获取ID
                developUser = developUserRepository.save(developUser);
            }
            List<DevelopUserRecord> list1 = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                DevelopUserRecord developUserRecord = new DevelopUserRecord();
                if (Objects.nonNull(list.get(j).getId())){
                    developUserRecord =  developUserRecordRepository.getOne(list.get(j).getId());
                }
                CopyUtils.copyProperties(list.get(j),developUserRecord);
                developUserRecord.setDevelopId(developId);
                developUserRecord.setChildrenId(childrenList.get(i).getId());
                developUserRecord.setDevelopUserId(developUser.getId());
                list1.add(developUserRecord);
            }
            developUserRecordRepository.saveAll(list1);

            String sql = String.format("SELECT count(id) FROM `tc_develop_review_item` where developId=  '%s' ",developId);
            List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
            int developCount = Integer.parseInt(String.valueOf(objects1.get(0)));

            String sql2 = String.format("SELECT count(id) FROM `tc_develop_user_record` where developId=  '%s' ",developId);
            sql2 += String.format("and  childrenId=  '%s' ",childrenList.get(i).getId());
            List<Object[]> objects2 = baseNativeSqlRepository.sqlArrayList(sql2);
            int developNumber = Integer.parseInt(String.valueOf(objects2.get(0)));


            developUser.setChildrenId(childrenList.get(i).getId());
            developUser.setDevelopId(developId);
            developUser.setDevelopCount(developCount);
            developUser.setDevelopNumber(developNumber);
            developUser.setRemarks(remarks);
            developUser.setClassId(ids1[i]);
            developUser.setCreatedBy(realName);
            developUserRepository.save(developUser);
            Children children  = childrenRepository.getOne(childrenList.get(i).getId());
            feedsService.save(staff.getId(), childrenList.get(i).getId(), staff.getAreaId(), "", FeedsConstant.DEVELOP_REVIEW, children.getName()+"的"+developReview.getName(), "","", "", developUser.getId());
        }
    }
}
